package com.xu.timer;


import java.util.concurrent.TimeUnit;

/**
 * @author:whh
 * @date: 2025-07-26 22:44
 * <p></p>
 */
public abstract class AbsTimerTask implements TimerTask{



    private final HashedWheelTimer hashedWheelTimer;

    private final Long delay;

    private final TimeUnit delayUnit;

    private final String taskName;
    protected volatile boolean cancel = false;

    private volatile Timeout timeout;

    AbsTimerTask(HashedWheelTimer hashedWheelTimer, String taskName,Long delay,TimeUnit delayUnit) {
        this.hashedWheelTimer = hashedWheelTimer;
        this.taskName=taskName;
        this.delay = delay;
        this.delayUnit=delayUnit;
        start();
    }



    private void start() {
        this.timeout = hashedWheelTimer.newTimeout(this, delay, delayUnit);
    }

    public synchronized void cancel() {
        this.cancel = true;
        this.timeout.cancel();
    }



    @Override
    public void run(Timeout timeout) throws Exception {
        doTask(timeout);
    }

    @Override
    public String taskName() {
        return taskName;
    }

    @Override
    public Long delay() {
        return delay;
    }

    @Override
    public TimeUnit delayUnit() {
        return delayUnit;
    }

    @Override
    public boolean isCancel() {
        return cancel;
    }

    public abstract void doTask(Timeout timeout);
}
